//
//  ContactDetail.m
//  Speedater
//
//  Created by NgoThang on 1/2/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ContactDetail.h"
#import "Start.h"
#import "Radar.h"
#import "MailCompose.h"
#import "AppDelegate.h"
#import "asyncimageview.h"
#import "JSON.h"

@interface ContactDetail (Private)

- (void)cleanup;

@end

@implementation ContactDetail (Private)

- (void)cleanup
{
    self.myScrollView = nil;
    self.myTabBar = nil;
    self.friendUsername = nil;
    self.avatarImageView = nil;
    self.genderImageView = nil;
    self.lightImageView = nil;
    self.usernameLabel = nil;
    self.cityLabel = nil;
    self.searchGenderLabel = nil;
    self.hairColorLabel = nil;
    self.sizeLabel = nil;
    self.weightLabel = nil;
    self.profesionLabel = nil;
    self.hobbiesLabel = nil;
    self.aboutMeLabel = nil;
    self.addContactButton = nil;
    self.removeContactButton = nil;
    self.viewOnRadarButton = nil;
    self.sendMailButton = nil;
}

@end


@implementation ContactDetail

@synthesize myScrollView;
@synthesize myTabBar;
@synthesize friendUsername;
@synthesize avatarImageView, genderImageView, lightImageView;
@synthesize usernameLabel, cityLabel, searchGenderLabel, hairColorLabel, sizeLabel, weightLabel, profesionLabel, hobbiesLabel, aboutMeLabel;
@synthesize addContactButton, removeContactButton, viewOnRadarButton, sendMailButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"CONTACTDETAIL -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (IBAction)addContactButtonClick:(id)sender
{
    // load profile mode
    requestMode = 2;
    
    NSString *postString = [NSString stringWithFormat:@"op=markFriend&username=%@&friendUsername=%@",
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                            friendUsername];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData]; 
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (IBAction)removeContactButtonClick:(id)sender
{
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
                                                      message:NSLocalizedString(@"Are you sure, you want to remove it?", nil)
                                                     delegate:self
                                            cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                            otherButtonTitles:NSLocalizedString(NSLocalizedString(@"OK", nil), nil), nil];
    [message show];
    [message release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex)
    {
        // load profile mode
        requestMode = 3;
        
        NSString *postString = [NSString stringWithFormat:@"op=removeFriend&username=%@&friendUsername=%@",
                                [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                                friendUsername];
        NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
        NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:postData]; 
        [request setTimeoutInterval:60.0];
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        if (conn) {
            // init data    
            responseData = [[NSMutableData data ] retain];
            
            // loading
            UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
            HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
            [theWindow addSubview:HUD];
            HUD.delegate = self;
            [HUD show:YES];
        }
        [conn release];
    }
}

- (IBAction)viewOnRadarButtonClick:(id)sender
{
    [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:YES];
    Radar *radar = (Radar *)[[[self.tabBarController.viewControllers objectAtIndex:1] viewControllers] objectAtIndex: 0];
    NSString *fusername = [[NSString alloc] initWithString:friendUsername];
    radar.friendUsername = fusername;
    [fusername release];
    self.tabBarController.selectedIndex = 1;
}

- (IBAction)sendMailButtonClick:(id)sender
{
    [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
    self.tabBarController.selectedIndex = 3;
    
    MailCompose *mailCompose = [[MailCompose alloc] init];
    mailCompose.username = [NSString stringWithString:friendUsername];
    [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] pushViewController:mailCompose animated:YES];
    [mailCompose release];
}

- (void)loadContactProfile
{    
    // load profile mode
    requestMode = 1;
    
    NSString *postString = [NSString stringWithFormat:@"op=loadprofile&username=%@&username_psudo=%@", 
                            friendUsername, 
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"]];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData]; 
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (void)goStart
{
    // goto Start form
    self.tabBarController.selectedIndex = 0;
    
    UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
    for (UIViewController *vc in nav1.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"RADAR -> popToViewController: %@", vc);
            [nav1.topViewController.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dismissActionSheet:(id)sender
{
    [myActionSheet dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)avatarClick
{
    myActionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                delegate:nil
                                       cancelButtonTitle:nil
                                  destructiveButtonTitle:nil
                                       otherButtonTitles:nil];
    
    [myActionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:avatarImageView.image] autorelease];
    imageView.frame = CGRectMake(10, 50, 300, 300);
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [myActionSheet addSubview:imageView];
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"zurück"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(240, 7.0f, 70.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [myActionSheet addSubview:closeButton];
    [closeButton release];
    
    [myActionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [myActionSheet setBounds:CGRectMake(0, 0, 320, 685)];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"CONTACTDETAIL -> viewDidLoad");
    [super viewDidLoad];
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background_blue.png"]]];
    
    // scroll view
    [self.myScrollView setContentSize:CGSizeMake(320, 490)];
    
    // navigation title
    self.title = friendUsername;
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // selected tab
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:1]];
    
    // avatar image click
    UITapGestureRecognizer *tgr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarClick)] autorelease];
    [self.avatarImageView addGestureRecognizer:tgr];
    [avatarImageView setUserInteractionEnabled:YES];
    
    // default value
    [[NSUserDefaults standardUserDefaults] setObject:friendUsername forKey:@"contact_friend"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)viewDidUnload
{
    //NSLog(@"CONTACTDETAIL -> viewDidUnload");
    [self cleanup];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"CONTACTDETAIL -> viewWillAppear");
    //NSLog(@"CONTACTDETAIL -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:2 withViewController:self];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
    
    // get avatar image
    AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(16, 10, 47, 43)];
    asyncImage.tag = 999;
	NSURL *avatarURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@avatar/%@", 
                                              [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"], 
                                              friendUsername]];
	[asyncImage loadImageFromURL:avatarURL];
    [asyncImage setForImage:avatarImageView];
    avatarImageView.contentMode = UIViewContentModeScaleAspectFit;
    [asyncImage release];
    
    // load contact profile
    [self loadContactProfile];
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark TabBar

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:1]];
    switch (item.tag) {
        case 0:
            [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 1;
            break;
        case 1:
            break;
        case 2: 
            [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 3;
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSMutableDictionary *results = [responseString JSONValue];
    [responseString release];
    
    NSString *status = nil;
    switch (requestMode) {
        case 1:
            
            if ([[results objectForKey:@"myAlter"] length]) {
                [usernameLabel setText:[NSString stringWithFormat:@"%@ (%@)", friendUsername, [results objectForKey:@"myAlter"]]];
            } 
            else {
                [usernameLabel setText:friendUsername];
            }
            [cityLabel setText:[results objectForKey:@"myWohnort"]];
            [searchGenderLabel setText:[results objectForKey:@"mySuche"]];
            [sizeLabel setText:[results objectForKey:@"myGrobe"]];
            [weightLabel setText:[results objectForKey:@"myGewicht"]];
            [profesionLabel setText:[results objectForKey:@"myBeruf"]];
            [hairColorLabel setText:[results objectForKey:@"myHaarfarbe"]];
            [hobbiesLabel setText:[results objectForKey:@"myHobbies"]];
            [aboutMeLabel setText:[AppDelegate decodeText:[results objectForKey:@"myAboutme"]]];
            
            if ([[results objectForKey:@"isMale"] intValue])
            {
                [genderImageView setImage:[UIImage imageNamed:@"ico_male.png"]];
            }
            else 
            {
                [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background_pink.png"]]];
                [genderImageView setImage:[UIImage imageNamed:@"ico_female.png"]];
            }
            if([[results objectForKey:@"myAmpel"] isEqualToString:@"0"])[lightImageView setImage:[UIImage imageNamed:@"light_red.png"]];    
            if([[results objectForKey:@"myAmpel"] isEqualToString:@"1"])[lightImageView setImage:[UIImage imageNamed:@"light_yellow.png"]];    
            if([[results objectForKey:@"myAmpel"] isEqualToString:@"2"])[lightImageView setImage:[UIImage imageNamed:@"light_green.png"]]; 
            
            // check marked
            if ([[results objectForKey:@"isMarked"] intValue]) {
                addContactButton.hidden = TRUE;
                removeContactButton.hidden = FALSE;
            }
            else {
                removeContactButton.hidden = TRUE;
                addContactButton.hidden = FALSE;
            }
            
            break;
        case 2:
            status = [results objectForKey:@"status"];
            if ([status isEqualToString:@"0"]) 
            {
                UIAlertView *alert = [[UIAlertView alloc] 
                                      initWithTitle:nil 
                                      message:NSLocalizedString(@"Incidents occur, please check again!", nil) 
                                      delegate:nil 
                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                      otherButtonTitles:nil];
                [alert show];	
                [alert release]; 
                
            }
            else 
            {
                [self goBack];
                
                UIAlertView *alert = [[UIAlertView alloc] 
                                      initWithTitle:nil 
                                      message:NSLocalizedString(@"Bookmark successfully!", nil) 
                                      delegate:nil 
                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                      otherButtonTitles:nil];
                [alert show];	
                [alert release];
            }
            
            break;
        case 3:
            status = [results objectForKey:@"status"];
            if ([status isEqualToString:@"0"]) 
            {
                UIAlertView *alert = [[UIAlertView alloc] 
                                      initWithTitle:nil 
                                      message:NSLocalizedString(@"Incidents occur, please check again!", nil) 
                                      delegate:nil 
                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                      otherButtonTitles:nil];
                [alert show];	
                [alert release]; 
                
            }
            else 
            {
                [self goBack];
                
                UIAlertView *alert = [[UIAlertView alloc] 
                                      initWithTitle:nil 
                                      message:NSLocalizedString(@"Remove successfully!", nil) 
                                      delegate:nil 
                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                      otherButtonTitles:nil];
                [alert show];	
                [alert release];
            }
            break;
        default:
            break;
    }
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
